/*
 * @Description: 存储服务，存储格式为{}[],
 * @Author: wws1993
 * @Date: 2020-11-25 17:40:22
 * @LastEditTime: 2020-11-26 15:38:57
 * @LastEditors: wws1993
 * @FilePath: \todoManager\src\service\ServiceForLocalStorage.ts
 */

class ServiceForLocalStorage {
  public BASEHEADE: string = 'TODO-MANAGE-';

  /** 当前key集合 */
  get currentKeys() {
    let keys = Object.keys(localStorage);
    keys = keys.filter(k => k.includes(this.BASEHEADE));
    keys = keys.map(k => k.substring(this.BASEHEADE.length, k.length - 1));

    return keys;
  }

  /** 检查是否重名
   * @param key 检查字段
   * @returns true-无重复 false-重复
   */
  public checkRepeat(key: string) {
    return this.currentKeys.findIndex(k => k === key) === -1;
  }

  public set(key: string, value: any) {
    return new Promise((resolve, reject) => {
      try {
        if (Object.prototype.toString.call(value).indexOf('Array') === -1) {
          console.group();
          console.log(`%c存储类型错误，请检查`, 'color:red');
          console.log(value);
          console.groupEnd();
          return reject();
        }

        localStorage.setItem(`${this.BASEHEADE}${key}`, JSON.stringify(value));
        resolve();
      } catch (err) {
        reject(err);
      }
    });
  }

  public get(key: string): null | anyObject[] {
    try {
      const data = localStorage.getItem(`${this.BASEHEADE}${key}`);
      return data ? JSON.parse(data) : null;
    } catch (err) {
      throw Error(err);
    }
  }

  public delete(key: string) {
    return new Promise((resolve, reject) => {
      try {
        localStorage.removeItem(`${this.BASEHEADE}${key}`);
        resolve();
      } catch (err) {
        reject(err);
      }
    });
  }
}

export default new ServiceForLocalStorage();
